<?php

App::uses('AppController', 'Controller');

class UsersController extends AppController {
    
    public $pageTitle = "Korisnici";
    
    public $uses = array('User', 'Client');
    
    public $paginate = array(
        'limit' => ITEMS_PER_PAGE
    );
    
    public function index() {
        $filter = $this->parseFilterData('User');
        
        $this->paginate['order'] = "{$filter->sortBy} {$filter->sortDir}";
        $users = $this->paginate('User', $filter->conditions);
        
        $this->set('users',    $users);
        
        $this->setFilterData($filter);
    }
    
    private function setCommonData() {
        $this->set('clients', $this->Client->find('list'));
    }
    
    public function create() {
        $this->setCommonData();
        $this->set('data', $this->User->create());
        $this->render('form');
    }
        
    public function edit($id) {
        $this->setCommonData();
        $this->set('data', $this->User->findById($id));
        $this->render('form');
    }
    
    public function save() {
        $data = $this->data;
        if (! empty($data)) {
            
            // validate password
            if (! empty($data['User']['password'])) {
                if ($data['User']['password'] != $data['User']['password2']) {
                    $this->setCommonData();
                    $this->setFlash('Unete lozinke se ne podudaraju');
                    $this->set('data', $data);
                    return $this->render('form');
                } else {
                    $data['User']['password'] = $this->Auth->password($data['User']['password']);
                }
            } else {
                unset($data['User']['password']);
            }
            
            
            $this->User->create($data);
            
            if (! $this->User->validates()) {
                $this->setCommonData();
                $this->set('data', $data);
                $this->setFlash('Uneti podaci nisu validni!');
                return $this->render('form');
            }
            
            if (! $this->User->save($data)) {
                $this->setCommonData();
                $this->set('data', $data);
                $this->setFlash('Čuvanje nije uspelo!');
                return $this->render('form');
            }
            
            $this->setFlash('Korisnik je uspešno sačuvan.', 'ok');
            $this->redirect("/users/edit/" . $this->User->id);
        }
        $this->redirect("index");
    }
    
    public function remove($id) {
        if ($this->User->delete($id)) {
            $this->setFlash('Korisnik je obrisan.', 'ok');
        } else {
            $this->setFlash('Korisnik nije obrisan.');
        }
        
        $this->redirect("index");
    }
    
}
